import './ContentList.scss';
import React from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux'
import ListItem from './ListItem/ListItem.jsx';
import contentListAction from '../../actions/contentListAction'
import ScrollView from '../../../../components/scrollView/scrollView.jsx';
/**
 * @constructor <ContentList />
 * @description
 */
class ContentList extends React.Component {
    constructor(props) {
        super(props);
        // 记录当前页码
        this.page = 0;
        // 标识页面是否可以滚动
        this.state = {
          isend: false
        };
        this.fetchData();
    }



    /**
     * 获取数据，存入store
     *
     * @return {[type]} [description]
     */
    fetchData() {
      this.props.contentListAction(this.page);
    }

    onLoadPage() {
        this.page++;
        // 最多滚动3页3次
        if (this.page >= 3) {
            this.setState({
                isend: true
            });
        } else {
            this.fetchData(this.page);
        }
    }

    // onLoadPage() {
    //   let clientHeight = document.documentElement.clientHeight;
    //   let scrollTop = document.documentElement.scrollTop;
    //   let scrollHeight = document.body.scrollHeight;

    //   let proloadDis = 30;

    //   if(scrollTop + clientHeight >= scrollHeight - proloadDis) {
    //     this.params.page ++;
    //     if(this.params.page >= this.params.totalPage) {
    //       // 加载完毕
    //       this.setState({
    //         isLoadAll: true,
    //         loadingState: '已完成'
    //       })
    //     } else {
    //       this.fetchData()
    //     }

    //   }

    // }

    // componentDidMount () {
    //   window.addEventListener('scroll', this.onLoadPage.bind(this));
    // }



    /**
     * 渲染推荐列表
     * @return {[type]} [description]
     */
    renderItems() {
      let list = this.props.list
      return list.map((item, index)=>{
          return <ListItem  key={index} itemData={item}></ListItem>
      });
    }
    render(){

        return (
            <div className="content-list">
                <div className="content-list-header">
                  <h4 className="list-title">
                      <span className="title-line"></span>
                      <span>附近商家</span>
                      <span className="title-line"></span>
                  </h4>
                </div>
                <ScrollView dis="content" loadCallback={this.onLoadPage.bind(this)} isend={this.state.isend}>
                    {this.renderItems()}
                </ScrollView>

                <div className="loading-state">
                  {this.state.loadingState}
                </div>
            </div>
        );
    }
}

export default connect(
  (state) => {
    return {
      list: state.contentListReducer.list
    }
  },
  (dispatch) => {
    return {
      contentListAction: bindActionCreators(contentListAction, dispatch)
    }
  }
)(ContentList)
